'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { toast } from '@/hooks/use-toast';
import { 
  Eye, 
  EyeOff, 
  Settings, 
  Users, 
  ShoppingCart,
  Shield,
  Edit,
  BarChart3,
  Activity,
  TrendingUp
} from 'lucide-react';

interface MinerTypeConfig {
  id: string;
  miner_type: string;
  is_visible_frontend: boolean;
  is_visible_admin: boolean;
  display_name: string;
  description: string;
  display_order: number;
  is_enabled: boolean;
  is_purchasable: boolean;
  updated_by: string;
  notes: string;
  created_at: string;
  updated_at: string;
}

interface MinerTypeStats {
  miner_type: string;
  total_created: number;
  active_count: number;
  total_staked: number;
  is_visible_frontend: boolean;
  is_enabled: boolean;
  is_purchasable: boolean;
}

interface UpdateConfigRequest {
  is_visible_frontend?: boolean;
  is_visible_admin?: boolean;
  display_name?: string;
  description?: string;
  display_order?: number;
  is_enabled?: boolean;
  is_purchasable?: boolean;
  notes?: string;
}

export default function MinerConfigPage() {
  const { currentChain } = useChain();
  const queryClient = useQueryClient();
  const [selectedConfig, setSelectedConfig] = useState<MinerTypeConfig | null>(null);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [editForm, setEditForm] = useState<UpdateConfigRequest>({});

  // Fetch miner type configurations
  const { data: configs, isLoading } = useQuery<MinerTypeConfig[]>({
    queryKey: ['miner-configs', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/miner-config/types');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch miner type statistics
  const { data: stats } = useQuery<MinerTypeStats[]>({
    queryKey: ['miner-config-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/miner-config/stats');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Toggle frontend visibility mutation
  const toggleVisibilityMutation = useMutation({
    mutationFn: async (minerType: string) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.post(`/api/v1/admin/miner-config/types/${minerType}/toggle-frontend`);
      return response.data;
    },
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['miner-configs'] });
      queryClient.invalidateQueries({ queryKey: ['miner-config-stats'] });
      toast({
        title: "Success",
        description: `${data.miner_type} visibility updated to ${data.is_visible_frontend ? 'visible' : 'hidden'}`,
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to toggle visibility",
        variant: "destructive",
      });
    },
  });

  // Update configuration mutation
  const updateConfigMutation = useMutation({
    mutationFn: async ({ minerType, data }: { minerType: string; data: UpdateConfigRequest }) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.put(`/api/v1/admin/miner-config/types/${minerType}`, data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['miner-configs'] });
      queryClient.invalidateQueries({ queryKey: ['miner-config-stats'] });
      setShowEditDialog(false);
      setSelectedConfig(null);
      setEditForm({});
      toast({
        title: "Success",
        description: "Miner type configuration updated successfully",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to update configuration",
        variant: "destructive",
      });
    },
  });

  const handleToggleVisibility = (minerType: string) => {
    toggleVisibilityMutation.mutate(minerType);
  };

  const handleEditConfig = (config: MinerTypeConfig) => {
    setSelectedConfig(config);
    setEditForm({
      is_visible_frontend: config.is_visible_frontend,
      is_visible_admin: config.is_visible_admin,
      display_name: config.display_name,
      description: config.description,
      display_order: config.display_order,
      is_enabled: config.is_enabled,
      is_purchasable: config.is_purchasable,
      notes: config.notes,
    });
    setShowEditDialog(true);
  };

  const handleUpdateConfig = () => {
    if (!selectedConfig) return;
    
    updateConfigMutation.mutate({
      minerType: selectedConfig.miner_type,
      data: editForm
    });
  };

  const getMinerTypeColor = (type: string) => {
    switch (type) {
      case 'M0': return 'bg-slate-100 text-slate-800';
      case 'M1': return 'bg-green-100 text-green-800';
      case 'M2': return 'bg-blue-100 text-blue-800';
      case 'M3': return 'bg-purple-100 text-purple-800';
      case 'M4': return 'bg-orange-100 text-orange-800';
      case 'M5': return 'bg-red-100 text-red-800';
      case 'M6': return 'bg-pink-100 text-pink-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatsForType = (minerType: string) => {
    return stats?.find(s => s.miner_type === minerType);
  };

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
          {/* Header */}
          <div>
            <h1 className="text-3xl font-bold tracking-tight">Miner Type Configuration</h1>
            <p className="text-muted-foreground">
              Manage visibility and settings for miner types in the frontend DApp
            </p>
          </div>

          {/* Overview Stats */}
          {stats && (
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Total Types</CardTitle>
                  <Settings className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.length}</div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Frontend Visible</CardTitle>
                  <Eye className="h-4 w-4 text-green-600" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-green-600">
                    {stats.filter(s => s.is_visible_frontend).length}
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Purchasable</CardTitle>
                  <ShoppingCart className="h-4 w-4 text-blue-600" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-blue-600">
                    {stats.filter(s => s.is_purchasable).length}
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">Total Active</CardTitle>
                  <Activity className="h-4 w-4 text-purple-600" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold text-purple-600">
                    {stats.reduce((sum, s) => sum + s.active_count, 0)}
                  </div>
                </CardContent>
              </Card>
            </div>
          )}

          {/* Miner Types Configuration */}
          <Card>
            <CardHeader>
              <CardTitle>Miner Types Configuration</CardTitle>
              <CardDescription>
                Control visibility and settings for each miner type
              </CardDescription>
            </CardHeader>
            <CardContent>
              {isLoading ? (
                <div className="text-center p-8">Loading configurations...</div>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b">
                        <th className="text-left p-4">Type</th>
                        <th className="text-left p-4">Display Name</th>
                        <th className="text-center p-4">Frontend Visible</th>
                        <th className="text-center p-4">Enabled</th>
                        <th className="text-center p-4">Purchasable</th>
                        <th className="text-center p-4">Statistics</th>
                        <th className="text-center p-4">Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {configs?.map((config) => {
                        const typeStats = getStatsForType(config.miner_type);
                        return (
                          <tr key={config.id} className="border-b hover:bg-muted/50">
                            <td className="p-4">
                              <span className={`px-2.5 py-0.5 rounded-full text-xs font-medium ${getMinerTypeColor(config.miner_type)}`}>
                                {config.miner_type}
                              </span>
                            </td>
                            <td className="p-4">
                              <div>
                                <div className="font-medium">{config.display_name}</div>
                                <div className="text-sm text-muted-foreground">{config.description}</div>
                              </div>
                            </td>
                            <td className="p-4 text-center">
                              <Switch
                                checked={config.is_visible_frontend}
                                onCheckedChange={() => handleToggleVisibility(config.miner_type)}
                                disabled={toggleVisibilityMutation.isPending}
                              />
                            </td>
                            <td className="p-4 text-center">
                              {config.is_enabled ? (
                                <span className="text-green-600">✓</span>
                              ) : (
                                <span className="text-red-600">✗</span>
                              )}
                            </td>
                            <td className="p-4 text-center">
                              {config.is_purchasable ? (
                                <span className="text-green-600">✓</span>
                              ) : (
                                <span className="text-red-600">✗</span>
                              )}
                            </td>
                            <td className="p-4">
                              {typeStats && (
                                <div className="text-sm space-y-1">
                                  <div className="flex items-center gap-1">
                                    <Users className="h-3 w-3" />
                                    <span>Total: {typeStats.total_created}</span>
                                  </div>
                                  <div className="flex items-center gap-1">
                                    <Activity className="h-3 w-3" />
                                    <span>Active: {typeStats.active_count}</span>
                                  </div>
                                  <div className="flex items-center gap-1">
                                    <TrendingUp className="h-3 w-3" />
                                    <span>Staked: {Math.round(typeStats.total_staked).toLocaleString()}</span>
                                  </div>
                                </div>
                              )}
                            </td>
                            <td className="p-4 text-center">
                              <Button
                                variant="outline"
                                size="sm"
                                onClick={() => handleEditConfig(config)}
                              >
                                <Edit className="h-3 w-3" />
                              </Button>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Edit Configuration Modal */}
          {showEditDialog && selectedConfig && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
              <Card className="w-full max-w-2xl max-h-[80vh] overflow-y-auto">
                <CardHeader>
                  <CardTitle>Edit {selectedConfig.miner_type} Configuration</CardTitle>
                  <CardDescription>
                    Update settings for {selectedConfig.display_name}
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium">Display Name</label>
                      <input
                        type="text"
                        value={editForm.display_name || ''}
                        onChange={(e) => setEditForm({ ...editForm, display_name: e.target.value })}
                        className="w-full mt-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="text-sm font-medium">Display Order</label>
                      <input
                        type="number"
                        value={editForm.display_order || 0}
                        onChange={(e) => setEditForm({ ...editForm, display_order: parseInt(e.target.value) })}
                        className="w-full mt-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="text-sm font-medium">Description</label>
                    <textarea
                      value={editForm.description || ''}
                      onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                      rows={3}
                      className="w-full mt-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-3">
                      <div className="flex items-center justify-between">
                        <label className="text-sm font-medium">Frontend Visible</label>
                        <Switch
                          checked={editForm.is_visible_frontend || false}
                          onCheckedChange={(checked) => setEditForm({ ...editForm, is_visible_frontend: checked })}
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <label className="text-sm font-medium">Admin Visible</label>
                        <Switch
                          checked={editForm.is_visible_admin || false}
                          onCheckedChange={(checked) => setEditForm({ ...editForm, is_visible_admin: checked })}
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <label className="text-sm font-medium">Enabled</label>
                        <Switch
                          checked={editForm.is_enabled || false}
                          onCheckedChange={(checked) => setEditForm({ ...editForm, is_enabled: checked })}
                        />
                      </div>
                    </div>
                    <div className="space-y-3">
                      <div className="flex items-center justify-between">
                        <label className="text-sm font-medium">Purchasable</label>
                        <Switch
                          checked={editForm.is_purchasable || false}
                          onCheckedChange={(checked) => setEditForm({ ...editForm, is_purchasable: checked })}
                        />
                      </div>
                    </div>
                  </div>

                  <div>
                    <label className="text-sm font-medium">Admin Notes</label>
                    <textarea
                      value={editForm.notes || ''}
                      onChange={(e) => setEditForm({ ...editForm, notes: e.target.value })}
                      rows={2}
                      placeholder="Internal notes for admins..."
                      className="w-full mt-1 px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div className="flex justify-end gap-2 pt-4">
                    <Button
                      variant="outline"
                      onClick={() => {
                        setShowEditDialog(false);
                        setSelectedConfig(null);
                        setEditForm({});
                      }}
                    >
                      Cancel
                    </Button>
                    <Button
                      onClick={handleUpdateConfig}
                      disabled={updateConfigMutation.isPending}
                    >
                      {updateConfigMutation.isPending ? 'Updating...' : 'Update Configuration'}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </div>
          )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}